import { createRouter, createWebHistory } from 'vue-router'; // Vue 3 的导入方式
import LoginPage from '@/views/LoginPage.vue'; // 导入登录页面组件
import IndexPage from '@/views/IndexPage.vue'; // 导入首页组件
import AddGood from '@/components/AddGood.vue';
import EditProfile from "@/components/EditProfile.vue";
import RecommendPage from "@/components/RecommendPage.vue";
import CategoryPage from "@/components/CategoryPage.vue";
import ChatPage from "@/components/ChatPage.vue";
import ProfilePage from "@/components/ProfilePage.vue";

// 路由配置
const routes = [
    {
        path: '/',
        name: 'LoginPage',
        component: LoginPage,
        meta: { requiresGuest: true }
    },
    {
        path: '/index',
        component: IndexPage,
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                redirect: 'recommend'
            },
            {
                path: 'recommend',
                name: 'RecommendPage',
                component: RecommendPage,
            },
            {
                path: 'category',
                component: CategoryPage,
            },
            {
                path: 'chat',
                component: ChatPage,
            },
            {
                path: 'profile',
                name:'ProfilePage',
                component: ProfilePage,
            }
        ]
    },
    {
        path: '/good/add',
        name: 'AddGood',
        component: AddGood,
        meta: { requiresAuth: true }
    },
    {
        path: '/edit',
        name: 'EditProfile',
        component: EditProfile,
        meta: { requiresAuth: true }
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/'
    },
    {
        path: '/good/detail/:id', // 动态路由参数
        name: 'GoodDetail',
        component: () => import('@/views/GoodDetail.vue')
    }
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(), // 使用 history 模式
    routes // 路由配置
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem('token'); // 从 sessionStorage 获取 token

    if (to.matched.some(record => record.meta.requiresAuth) && !token) {
        // 如果路由需要登录且 token 不存在，则重定向到登录页面
        next({ name: 'LoginPage' });
    } else if (to.matched.some(record => record.meta.requiresGuest) && token) {
        // 如果路由仅允许未登录用户访问且 token 存在，则重定向到首页的推荐页
        next({ name: 'RecommendPage' }); // 修改这里：跳转到子路由
    } else {
        // 否则继续导航
        next();
    }
});

export default router;